function [colorimage] = MakeCellMap(variables, alphaIdx, label, background, colortable, outfname, showflag)

if nargin < 6
    outfname =[];
end

if nargin < 7
    showflag = 0;
end
if ~strcmp(alphaIdx, 'all'), variables(~alphaIdx) = NaN; end

if length(unique(background)) > 1 % only adjust contrast of the background if it's not uniform gray/white/black
    background = background / max(max(background));
end
background = background * 255;

Ncolors=size(colortable,1);

cells(1:max(max(label)), 1:3) = 0;
cells2 = cells;
cells2(:) = 1;
for jj = 1:length(variables)
    if ~isnan(variables(jj))
        color = round(variables(jj) * (Ncolors-1) + 1);
        if color < 1; % n.b. this set of if statements brings values that are out of range into range - data is lost
            color = 1;
        else if color > Ncolors;
                color = Ncolors;
            end
        end
        cells(jj, 1:3) = colortable(color,1:3);
        cells2(jj, 1:3) = 0;
    end
end
warning off;
map = label2rgb(label, cells, 'k');
mask = label2rgb(label, cells2, 'w') ./ 255;

background_2 = repmat(background, [1 1 3]);
% for i=1:3, background_2(:,:,i) = background; end
background_2 = uint8(background_2); % this is just for safety. the scaling previously shoud guarantee that the values are in uint8 range
colorimage = background_2 .* mask;
colorimage = imadd(colorimage, map);

warning on;

if showflag == 1;
    figure;
    imshow(colorimage);
end

if ~isempty(outfname)
    imwrite(colorimage, outfname);
end


